package cn.sq.musicserver.plug.model.qqmusicapi;

import cn.sq.musicserver.exception.PlugError;
import cn.sq.musicserver.music.entity.DownloadParam;
import cn.sq.musicserver.music.entity.SqMusic;
import cn.sq.musicserver.music.service.impl.SqMusicServiceImpl;
import cn.sq.musicserver.plug.entity.PlugLyicResult;
import cn.sq.musicserver.plug.entity.PlugSearchResult;
import cn.sq.musicserver.plug.hander.MusicInfoSearc;
import cn.sq.musicserver.plug.model.jsososo.entity.*;
import cn.sq.musicserver.plug.model.jsososo.entity.APISearchParam;
import cn.sq.musicserver.plug.model.jsososo.entity.APISearchResult;
import cn.sq.musicserver.plug.model.qqmusicapi.entity.*;
import cn.sq.musicserver.plug.model.qqmusicapi.service.QQMusicApiService;
import cn.sq.musicserver.set.entity.SqSet;
import cn.sq.musicserver.set.service.impl.SqSetServiceImpl;
import cn.sq.musicserver.utils.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.github.classgraph.utils.Join;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: SQ
 * Date: 2021/1/6
 * Time: 14:15
 * Description:
 */
@Slf4j
@Component
public class QQMusicApiHander  extends MusicInfoSearc {
    @Autowired
    QQMusicApiService qqMusicApiService;
    @Autowired
    SqSetServiceImpl setService;
    @Autowired
    SqMusicServiceImpl musicService;
    @Override
    public String PlugName() {
        return "QQMuiscApi";
    }
    @Override
    public String Plugversion() {
        return "1.0";
    }

    @Override
    public PlugSearchResult musicInfoSearc(Integer pagersize, Integer pageindex, String Keywords, File music, List<SqSet> set, Map<String, String> data) throws PlugError {
        APISearchParam apiSearchParam = new APISearchParam().setKey(Keywords).setPageNo(pageindex+"").setPageSize(pagersize+"").setT(data.get("type"));
        APISearchResult search = qqMusicApiService.search(apiSearchParam);
        PlugSearchResult plugSearchResult = new PlugSearchResult();
        if (search.getResult()==100){
            plugSearchResult.setPlugMusicSearchCount(search.getData().getTotal());
            plugSearchResult.setPlugMusicSearchIndex(search.getData().getPageNo());
            plugSearchResult.setPlugMusicSearchSize(search.getData().getPageSize());
            plugSearchResult.setPlugName(PlugName());
            List<APISearchResult.DataBean.ListBean> list = search.getData().getList();
            List<String> artists = new ArrayList<String>();
            ArrayList<PlugSearchResult.Song> songs = new ArrayList<>();
            for (APISearchResult.DataBean.ListBean listBean : list) {
                PlugSearchResult.Song song = new PlugSearchResult.Song();
                List<APISearchResult.DataBean.ListBean.SingerBean> singer = listBean.getSinger();
                singer.forEach(iteam->{
                    artists.add(iteam.getName());
                });
                String picUrl = qqMusicApiService.album(new APIAlbumParam().setAlbummid(listBean.getAlbummid())).getData().getPicUrl();
                song.setMusicArtists(Join.join(",", artists));
                song.setId(listBean.getSongmid())
                        .setMusicAlbum(listBean.getAlbumname())
                        .setPlugName(PlugName())
                        .setMusicName(listBean.getSongname())
                        .setMusicImage("http:"+picUrl);
                songs.add(song);
            }
            plugSearchResult.setSongs(songs);
        }
        return plugSearchResult;

    }

    @Override
    public SqMusic musicDownload(DownloadParam downloadParam) throws PlugError {
        APIDownloadParam apiDownloadParam = new APIDownloadParam().setIsRedirect("0").setType(downloadParam.getBr()).setId(downloadParam.getId());
        String lyircValue = null;
        String lyirctrans = null;
        //如果需要下载歌词
        if (downloadParam.isDownliadMusicLyric()) {
            LyricParam lyricParam = new LyricParam().setId(downloadParam.getId());
            PlugLyicResult plugLyicResult = MusiclyricDownload(lyricParam);
            lyircValue = plugLyicResult.getLyric();
            lyirctrans=plugLyicResult.getTrans();
        } else {
            lyircValue = downloadParam.getMusicLyric();
        }
        APIDownloadResult download = qqMusicApiService.download(apiDownloadParam);
        if (download.getResult() == 100) {
            String url = download.getData();
            String setVlaue = null;
            if (downloadParam.isTemp()) {
                //临时缓存
                setVlaue = setService.getOne(new QueryWrapper<SqSet>().eq("SetName", "SystemTempDownloadDir")).getSetVlaue();

            } else {
                setVlaue = setService.getOne(new QueryWrapper<SqSet>().eq("SetName", "SystemDownloadDir")).getSetVlaue();
            }
            String fileName = null;
            try {
                fileName = FileUtil.downloadToFile(url, setVlaue, downloadParam.getMusicName() + "-" + downloadParam.getMusicArtists());
            } catch (Exception e) {
                log.error("插件运行异常："+e.getMessage());
                throw new PlugError("插件运行io异常");
            }
            log.debug("下载地址：" + setVlaue);
            //是否下载图片
            if (downloadParam.isDownliadMusicImage()){
                String musicImage = downloadParam.getMusicImage();
                try {
                    downloadParam.setMusicImage(FileUtil.downloadToBase64(musicImage));
                } catch (IOException e) {
                    log.error("插件运行异常："+e.getMessage());
                    throw new PlugError("插件运行io异常");
                }
            }
            //保存到数据库中
            SqMusic sqMusic = new SqMusic()
                    .setMusicPath(fileName)
                    .setMusicName(downloadParam.getMusicName())
                    .setMusicAlbum(downloadParam.getMusicAlbum())
                    .setMusicArtists(downloadParam.getMusicArtists())
                    .setMusicImage(downloadParam.getMusicImage())
                    .setMusicDescribe(downloadParam.getMusicDescribe())
                    .setMusicLyric(lyircValue)
                    .setMusicCodeType(FileUtil.getFileSuffix(fileName).replaceAll(".", ""))
                    .setMusicTime(LocalDateTime.now())
                    .setMusicType(downloadParam.getMusicType())
                    .setMusicLyricTrans(lyirctrans);
            if (!downloadParam.isTemp()) {
                musicService.save(sqMusic);
            }

            return sqMusic;
        }
        return null;
    }

    @Override
    public PlugLyicResult MusiclyricDownload(LyricParam lyricParam) throws PlugError {
        APILyircResult lyric = qqMusicApiService.lyric(new APILyircParam().setSongmid(lyricParam.getId()));
        return  new PlugLyicResult().setLyric(lyric.getData().getLyric()).setTrans(lyric.getData().getTrans());
    }
}
